package core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import basic.PageInfo;
import basic.QuerySet;
import basic.SortInfo;
import common.Sequence;
import common.Service;
import common.Servlet;
import common.Validate;
import dict.CommonDict;
import dict.MbDict;
import dict.TransactionDict;
import dicts.GlobalDict;
import dicts.PaymentDict;
import entities.TBalance;
import entities.TMb;
import entities.TMerchant;
import entities.TSettle;
import interfaces.IBalanceService;
import interfaces.IMbService;
import interfaces.IMerchantService;
import interfaces.ISettleService;
import net.sf.json.JSONObject;
import util.LogUtil;
import utils.DateUtil;
import utils.StringUtil;

public class Settle extends Servlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public synchronized void process(HttpServletRequest request, HttpServletResponse response) throws Exception {

		System.out.println(DateUtil.format(new Date(), DateUtil.DATETIME) + " | 商户提现");

		// 初始化service
		IMerchantService merchantService = (IMerchantService) Service.create(IMerchantService.class);
		IMbService mbService = (IMbService) Service.create(IMbService.class);
		IBalanceService balanceService = (IBalanceService) Service.create(IBalanceService.class);
		ISettleService settleService = (ISettleService) Service.create(ISettleService.class);

		QuerySet<Object> querySet = new QuerySet<Object>();
		Map<String, Object> paramMap = Collections.synchronizedMap(new HashMap<String, Object>());
		JSONObject jsonResult = new JSONObject();

		// 初始化bean和属性
		TMerchant merchant = new TMerchant();
		TMb mb = new TMb();
		TBalance balance = new TBalance();
		TSettle settle = new TSettle();

		// 验证系统
		if (GlobalDict.LINUX.equalsIgnoreCase(System.getProperty("os.name")) && !CommonDict.HOST.equals(request.getServerName())) {
			response.getWriter().print(Validate.result(TransactionDict.ILLAGEL_ACCESS, TransactionDict.MESSAGES.get(TransactionDict.ILLAGEL_ACCESS)));
			return;
		}

		// 校验参数 ( 名称,值,校验模式,边界 )
		List<Object[]> parameterList = Collections.synchronizedList(new ArrayList<Object[]>());
		parameterList.add(new Object[] { "merNo", request.getParameter("merNo"), Validate.NOTEMPTY | Validate.EXCEEDLENGTH, 0, 50 });
		parameterList.add(new Object[] { "mbAmount", request.getParameter("mbAmount"), Validate.NOTEMPTY | Validate.ISNUMBER | Validate.EXCEEDNUMBER, 0, Integer.MAX_VALUE });

		JSONObject validateResult = Validate.validate(parameterList);
		LogUtil.settle(Validate.summary(parameterList));
		
		if (!StringUtil.isEmpty(validateResult)) {
			System.out.println ( validateResult.toString() ) ;
			response.getWriter().print(validateResult.toString());
			return;
		}

		mb.setMbAmount(new Double(request.getParameter("mbAmount")));

		// 交易商户存在和状态
		try {
			merchant = merchantService.fetch(request.getParameter("merNo"));
		} catch (Exception e) {
			response.getWriter().print(Validate.result(TransactionDict.MERCHANT_FETCH_EXCEPTION, TransactionDict.MESSAGES.get(TransactionDict.MERCHANT_FETCH_EXCEPTION)));
			return;
		}

		if (merchant == null) {
			response.getWriter().print(Validate.result(TransactionDict.MERCHANT_NOT_EXIST, TransactionDict.MESSAGES.get(TransactionDict.MERCHANT_NOT_EXIST)));
			return;
		}

		if (!merchant.getMerState().equals("1")) {
			response.getWriter().print(Validate.result(TransactionDict.MERCHANT_STATUS_EXCEPTION, TransactionDict.MESSAGES.get(TransactionDict.MERCHANT_STATUS_EXCEPTION)));
			return;
		}

		try {
			balance = balanceService.fetch(merchant.getMerNo());
		} catch (Exception e) {
			response.getWriter().print(Validate.result(TransactionDict.BALANCE_FETCH_EXCEPTION, TransactionDict.MESSAGES.get(TransactionDict.BALANCE_FETCH_EXCEPTION)));
			return;
		}

		try {
			settle = settleService.fetch(merchant.getMerNo());
		} catch (Exception e) {
			response.getWriter().print(Validate.result(TransactionDict.SETTLE_FETCH_EXCEPTION, TransactionDict.MESSAGES.get(TransactionDict.SETTLE_FETCH_EXCEPTION)));
			return;
		}

		if (mb.getMbAmount() < merchant.getMerLimit()) {
			response.getWriter().print(Validate.result(TransactionDict.AMOUNT_EXCEEDED_MERCHANT_LIMIT, TransactionDict.MESSAGES.get(TransactionDict.AMOUNT_EXCEEDED_MERCHANT_LIMIT)));
			return;
		}

		if (mb.getMbAmount() > settle.getSteTotal()) {
			response.getWriter().print(Validate.result(TransactionDict.BALANCE_NOT_ENOUGH, TransactionDict.MESSAGES.get(TransactionDict.BALANCE_NOT_ENOUGH)));
			return;
		}

		if (settle.getSteSm() * merchant.getMerVenture() / 100 > balance.getBalTotal()) {
			response.getWriter().print(Validate.result(TransactionDict.BALANCE_LESS_THAN_RISK_AMOUNT, TransactionDict.MESSAGES.get(TransactionDict.BALANCE_LESS_THAN_RISK_AMOUNT)));
			return;
		}
		
		// 提现周期条件是否满足
		try {
			paramMap = Collections.synchronizedMap(new HashMap<String, Object>());
			paramMap.put("merNo", merchant.getMerNo());
			paramMap.put("mbState", "1");
			SortInfo sortInfo = new SortInfo();
			sortInfo.setSortField("mbDate");
			sortInfo.setSortOrder(new Boolean(false));
			querySet.setPageInfo(new PageInfo(1, 1));
			querySet.setSortInfo(sortInfo);
			querySet.setParamMap(paramMap);
		} catch (Exception e) {
			response.getWriter().print(Validate.result(MbDict.MB_FETCH_EXCEPTION, MbDict.MESSAGES.get(MbDict.MB_FETCH_EXCEPTION)));
			return;
		}
		
		if(mbService.search(querySet).getResultList().size()>0){
			Long between=DateUtil.distanceDays(mbService.search(querySet).getResultList().get(0).getMbDate(), new Date());
			if(between<merchant.getMerFreq()){
				response.getWriter().print(Validate.result(TransactionDict.SETTLE_INTERVAL_LESS_THAN_MERCHANT_FREQUENCY, TransactionDict.MESSAGES.get(TransactionDict.SETTLE_INTERVAL_LESS_THAN_MERCHANT_FREQUENCY)));
				return;
			}
		}
		
		// 提现存在状态(是否之前还有未处理的项)
		try {
			paramMap = Collections.synchronizedMap(new HashMap<String, Object>());
			paramMap.put("merNo", merchant.getMerNo());
			paramMap.put("mbVstate", "0");
		} catch (Exception e) {
			response.getWriter().print(Validate.result(MbDict.MB_FETCH_EXCEPTION, MbDict.MESSAGES.get(MbDict.MB_FETCH_EXCEPTION)));
			return;
		}

		if (mbService.contain(paramMap)) {
			response.getWriter().print(Validate.result(MbDict.MB_ALREADY_EXIST, MbDict.MESSAGES.get(MbDict.MB_ALREADY_EXIST)));
			return;
		}

		try {
			mb.setMbNo(Sequence.mbSequence());
			mb.setMerNo(merchant.getMerNo());
			mb.setMbType(PaymentDict.MB_SETTLE);
			mb.setMbBank(merchant.getMerBank());
			mb.setMbBranch(merchant.getMerBranch());
			mb.setMbBanker(merchant.getMerBanker());
			mb.setMbAccount(merchant.getMerAccount());
			mb.setMbBankz("");
			mb.setMbBranchz("");
			mb.setMbBankerz("");
			mb.setMbAccountz("");
			mb.setMbState("1");
			mb.setMbDate(new Date());
			mb.setMbVstate("0");
			mb.setMbVdate(new Date(0L));
			mb.setMbRemark("");
			mbService.persist(mb);
		} catch (Exception e) {
			response.getWriter().print(Validate.result(MbDict.MB_PERSIST_EXCEPTION, MbDict.MESSAGES.get(MbDict.MB_PERSIST_EXCEPTION)));
			return;
		}

		jsonResult.put("code", MbDict.MB_SUCCESS);
		jsonResult.put("message", MbDict.MESSAGES.get(MbDict.MB_SUCCESS));
		response.getWriter().print(jsonResult.toString());
		return;
	}
}
